#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<string.h>

/*
read Thread 2
2,rd= 1 I write in func2 thread

read Thread 1
1,rd= 2 I write in func1 thread

2,rd= 3 I write in func2 thread

1,rd= 4 I write in func1 thread

This is func4 thread
This is func3 thread
2,rd= 5 I write in func2 thread

1,rd= 6 I write in func1 thread

2,rd= 7 I write in func2 thread

 *
 *
 */

pthread_rwlock_t rwlock;

FILE *fp;

void * read_func(void * arg){
	pthread_detach(pthread_self());
	printf("read Thread %d\n", (int)arg);
	char buf[32] = {0};
	while(1){
		pthread_rwlock_rdlock(&rwlock);
		//这里注意 任意一个线程读下，fp都会移动
		while(fgets(buf, 32, fp) != NULL){
			printf("%d,rd= %s\n", (int)arg, buf);
			usleep(1000);
		}
		pthread_rwlock_unlock(&rwlock);
		sleep(1);
	}
}

void * func3(void * arg){
	pthread_detach(pthread_self());
	printf("This is func3 thread\n");
	char s[] = "I write in func3 thread\n";
	while(1){
		//写锁
		pthread_rwlock_wrlock(&rwlock);
		int i = 0;
		while(i < strlen(s)){
			fputc(s[i], fp);
			i++;
			usleep(1);
		}
		pthread_rwlock_unlock(&rwlock);
		usleep(1);
	}
}

void * func4(void * arg){	
	pthread_detach(pthread_self());
	printf("This is func4 thread\n");
	char s[] = "I write in func4 thread\n";
	while(1){
		//写锁
		pthread_rwlock_wrlock(&rwlock);
		int i = 0;
		while(i < strlen(s)){
			fputc(s[i], fp);
			i++;
			usleep(1);
		}
		pthread_rwlock_unlock(&rwlock);
		usleep(1);
	}
}

int main(){
	pthread_t tid1, tid2, tid3, tid4;
	void * ret;

	//定一个临界资源 ：文件
	fp =  fopen("1.txt", "a+");
	if(fp == NULL){
		perror("fopen");
		return 0;
	}

	//初始化读写锁，只有动态初始化方式
	pthread_rwlock_init(&rwlock, NULL);

	//线程1：读文件
	pthread_create(&tid1, NULL, read_func, (void *)1);
	//线程2：读文件
	pthread_create(&tid2, NULL, read_func,(void *)2);
	//线程3：往文件写
	pthread_create(&tid3, NULL, func3, NULL);
	//线程2：往文件写
	pthread_create(&tid4, NULL, func4, NULL);

	//不让进程退出
	while(1){
		sleep(1);
	}
}
